package service

import (
	_ "errors"
	"go_code/gin-blog/dao/db"
	"go_code/gin-blog/model"
	"log"
	"strconv"
)

//获取文章和对应的分类
func GetArticleRecordList(pageNo, pageSize int) (articleRecordList []*model.ArticleRecord, err error) {
	//1.获取文章
	log.Println("1")
	articleInfoList, err := db.GetArticleList(pageNo, pageSize)
	log.Println(articleInfoList)
	if err != nil || len(articleInfoList) == 0 {
		return nil, err
	}
	//先获取文章中有多少分类
	categoryIds := getCategoryIds(articleInfoList)
	//2.根据分类的ID来获取categry结构体的切片
	categoryList, err := db.GetCategoryList(categoryIds)
	log.Println(categoryList)
	//fmt.Println(categoryIds)
	//fmt.Println("categoryList=", categoryList)
	//返回articleRecord结构体的集合
	for _, article := range articleInfoList {
		articleRecord := &model.ArticleRecord{
			ArticleInfo: *article,
		}
		categoryId := article.CategoryId
		for _, category := range categoryList {
			if categoryId == category.CategoryId {
				articleRecord.Category = *category
				break
			}
		}
		//fmt.Println(articleRecord)
		articleRecordList = append(articleRecordList, articleRecord)
	}
	return articleRecordList, nil

}

//获取文章列表中包含的类名
func getCategoryIds(articleList []*model.ArticleInfo) (ids []int64) {
label:
	for _, article := range articleList {
		categpryId := article.CategoryId
		for _, id := range ids {
			if id == categpryId {
				continue label
			}
		}
		ids = append(ids, categpryId)
	}
	return ids
}

//获取article_detail
func GetArticleDetail(articleId string) (articleDetail *model.ArticleDetail, err error) {
	//fmt.Println(id)
	articleDetail, err = db.GetArticleDetail(articleId) //拿到的是不含Category的detail对象
	if err != nil {
		return nil, err
	}

	//log.Println(articleDetail)

	//根据categoryId找到对应category对象
	categoryId := articleDetail.ArticleInfo.CategoryId
	//log.Println("categoryId=", categoryId)
	category, err := db.GetCategoryById(categoryId)
	articleDetail.Category = *category
	//fmt.Println(articleDetail)
	return articleDetail, nil

}

//根据articleId找到和他同类的文章。
//func GetArticleListByCategoryId(articleId string, pageNo, pageSize int) (relative_article []*model.ArticleInfo, err error) {
//	Id, _ := strconv.ParseInt(articleId, 10, 64)
//	categoryId, err := db
//}

func GetArticleByCategoryId(categoryId string) ([]*model.ArticleRecord, error) {
	Id, _ := strconv.ParseInt(categoryId, 10, 64)
	articleRecordList, err := db.GetArticleByCategoryId(Id)
	if err != nil {
		return nil, err
	}
	category, _ := db.GetCategoryById(Id)
	for _, article := range articleRecordList {
		article.Category = *category
	}

	return articleRecordList, nil
}
